<?php

namespace App\Http\Controllers\Mobile\Company;
use App\Models\Company\BuyResume;
use App\Models\Company\CompanyBasic;
use App\Models\Company\CompanyJob;
use App\Models\Company\CompanyUser;
use App\Models\Company\ResumeFavorite;
use App\Models\Personal\Resume;
use App\Models\Personal\ResumeSend;
use Illuminate\Http\Request;
use App\Models\Common\CollArea;
use App\Models\Common\CollOption;
use App\Facades\Style;
use Illuminate\Support\Facades\DB;
use Config;

class ResumeController extends CommonController{
    /**
     * 简历管理
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request){
        $user = auth()->guard('company')->user();
        //收到应聘简历
        $resumeSendCount = DB::table('resume_send as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->join('company_job as t2', 'log.job_id', '=', 't2.id')
            ->select('log.id')
            ->where('log.company_uid', $user->uid)
            ->where('log.status', '!=', 4)
            ->count();
        $user->resumeSendCount = ($resumeSendCount > 0) ? $resumeSendCount : 0;
        //企业人才库
        $favoriteCount = DB::table('resume_favorite as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->join('company_job as t2', 'log.job_id', '=', 't2.id')
            ->select('log.id')
            ->where('log.uid', $user->uid)
            ->where('log.status', '!=', 4)
            ->count();
        $user->favoriteCount = ($favoriteCount > 0) ? $favoriteCount : 0;
        //已购买简历
        $buyResumeCount = DB::table('buy_resume as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->select('log.id')
            ->where('log.company_uid', $user->uid)
            ->count();
        $user->buyResumeCount = ($buyResumeCount > 0) ? $buyResumeCount : 0;
        //浏览简历记录
        $browseResumeCount = DB::table('browse_resume as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->select('log.id')
            ->where('log.company_uid', $user->uid)
            ->count();
        $user->browseResumeCount = ($browseResumeCount > 0) ? $browseResumeCount : 0;
        //谁浏览过我
        $browseCompanyCount = DB::table('browse_company as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->select('log.id')
            ->where('log.company_uid', $user->uid)
            ->count();
        $user->browseCompanyCount = ($browseCompanyCount > 0) ? $browseCompanyCount : 0;

        return Style::view('mobile.company.resumeManage', compact('user'));
    }

    /**
     * 收到应聘简历
     * @param Request $request
     * @return mixed
     */
    public function message(Request $request){
        $user = auth()->guard('company')->user();
        //收到应聘简历
        $relist = DB::table('resume_send as log')
            ->join('resume as t1', 'log.resume_id', '=', 't1.id')
            ->join('company_job as t2', 'log.job_id', '=', 't2.id')
            ->select(
                'log.id', 'log.status', 'log.updated_at', 't1.name', 't1.sex', 't1.birthday',
                't1.education', 't1.homeaddress', 't2.job_title', 'log.resume_id', 'log.job_id','log.created_at'
            )
            ->where('log.company_uid', $user->uid)
            ->where(function ($query) use ($request) {
                if (strlen($request->keyWord) > 0) {
                    $query->where('t2.job_title', 'like', '%' . $request->keyWord . '%')->orWhere('t1.name', 'like', '%' . $request->keyWord . '%');
                }
            })
            ->where(function ($query) use ($request) {
                if (strlen($request->status) > 0) {
                    $query->where('log.status', $request->status);
                }
            })
            ->where('log.status', '!=', 4)
            ->orderBy('log.created_at', 'DESC')
            ->paginate(10);
        //print_r($queries );

        foreach ($relist as $v) {
            switch ($v->sex) {
                case "1":
                    $v->cnsex = '男';
                    break;
                case "2":
                    $v->cnsex = '女';
                    break;
                default:
                    $v->cnsex = '';
            }
            $v->education = CollOption::getOptionName($v->education, 'education');
            $v->homeaddress = CollArea::getAreaName($v->homeaddress);
            $v->birthday = birthday($v->birthday);
        }

        $status = $request->status;
        return Style::view('mobile.company.resumeMessage', compact('relist', 'status'));
    }

    /**
     * 删除简历库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request) {
        $user = auth()->guard('company')->user();
        $input['status'] = 4;//删除
        $result = ResumeSend::where('company_uid', $user->uid)->where('id', $request->id)->update($input);
        if ($result) {
            return response()->json(['status' => 200, 'message' => "删除简历成功"]);
        } else {
            return response()->json(['status' => 404, 'message' => "删除简历失败"]);
        }
    }

    /**
     * 返回简历是否被查看
     * @param $uid
     * @param $resumeId
     * @return int
     */
    public function lookResumeStatus($uid,$resumeId){
        if(!empty($uid)){
            $BuyResume = BuyResume::where('company_uid',$uid)->where('resume_id',$resumeId)->first();
            if($BuyResume){
                $lookStatus=1;//简历被查看过
            }else{
                $lookStatus=0;//简历未被查看过
            }
        }else{
            $lookStatus=0;//未登录
        }
        return $lookStatus;
    }

    /**
     * 查看企业简历数
     * @param $resumeId
     * @param $companyUid
     * @param $lookStatus
     * @return array
     */
    public function getContact($resumeId,$companyUid,$lookStatus){
        $status = [];
        //企业已登录
        if(!empty($companyUid) and is_numeric($companyUid)) {//登录
            //判断企业是会员，还是充值会员
            $companyUser = CompanyUser::select('viptime','vip_resume_number','resume_number')->where('uid',$companyUid)->first();

            if(empty($companyUser->viptime) || $this->timediff($companyUser->viptime) < 0){//不是会员 或 vip时间空或会员时间<0

                //查看简历数是否>0
                if($companyUser->resume_number > 0){

                    //查询联系方式
                    $resume = Resume::select('mobile','email','qq')->where('id',$resumeId)->where('resume_status',1)->first();
                    if($resume){
                        if($lookStatus==0){//未查看过
                            //减去一份简历
                            CompanyUser::where('uid',$companyUid)->decrement('resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid',$companyUid)->first();

                            //添加查看记录
                            $resume = Resume::select('uid','mobile','email','qq')->where('id',$resumeId)->first();
                            $input['company_uid'] = $companyUid;
                            $input['personal_uid'] = $resume->uid;
                            $input['resume_id'] = $resumeId;
                            $input['com_id'] =!empty($CompanyBasic) ? $CompanyBasic->id:'';

                            BuyResume::create($input);
                        }
                    }
                    $status = [1,$resume];
                }elseif($this->timediff($companyUser->viptime) < 0 and $companyUser->resume_number==0){//会员时间过期
                    if($lookStatus==1){//过期，但购买了非会员简历,最后一份简历，且已看过
                        $resume = Resume::select('uid','mobile','email','qq')->where('id',$resumeId)->first();
                        $status = [1,$resume];
                    }else{
                        $status = [2];//提示充值
                    }
                }else{
                    $status = [0];
                }

            }elseif($this->timediff($companyUser->viptime) > 0){//会员时间减去当前时间，>0表示未过期

                //查看会员期内简历数是否>0
                if($companyUser->vip_resume_number > 0){

                    //查询联系方式
                    $resume = Resume::select('mobile','email','qq')->where('id',$resumeId)->where('resume_status',1)->first();
                    if($resume){
                        if($lookStatus==0){//未查看过
                            //减去一份简历
                            CompanyUser::where('uid',$companyUid)->decrement('vip_resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid',$companyUid)->first();

                            //添加查看记录
                            $resume = Resume::select('uid','mobile','email','qq')->where('id',$resumeId)->first();
                            $data['company_uid'] = $companyUid;
                            $data['personal_uid'] = $resume->uid;
                            $data['resume_id'] = $resumeId;
                            $data['com_id'] =!empty($CompanyBasic) ? $CompanyBasic->id:'';

                            BuyResume::create($data);
                        }
                    }
                    $status = [1,$resume];
                }elseif($companyUser->resume_number > 0){//会员期内简历用完，购买了非会员简历
                    //查询联系方式
                    $resume = Resume::select('mobile','email','qq')->where('id',$resumeId)->where('resume_status',1)->first();
                    if($resume){
                        if($lookStatus==0){//未查看过
                            //减去一份简历
                            CompanyUser::where('uid',$companyUid)->decrement('resume_number');
                            $CompanyBasic = CompanyBasic::select('id')->where('uid',$companyUid)->first();

                            //添加查看记录
                            $resume = Resume::select('uid','mobile','email','qq')->where('id',$resumeId)->first();
                            $input['company_uid'] = $companyUid;
                            $input['personal_uid'] = $resume->uid;
                            $input['resume_id'] = $resumeId;
                            $input['com_id'] =!empty($CompanyBasic) ? $CompanyBasic->id:'';

                            BuyResume::create($input);
                        }
                    }
                    $status = [1,$resume];
                }else{
                    $status = [0];
                }

            }else{//提示注册企业用户无权限并充值
                $status = [0];
            }
            return $status;
        }
    }

    /**
     * 时间差
     * @param $time
     * @return int
     */
    public function timediff($time){
        $timezone = Config::get('app.timezone','PRC');
        date_default_timezone_set($timezone);
        $zero1 = strtotime(date("Y-m-d H:i:s",time()));
        $zero2 = strtotime($time);
        $time_c = $zero2-$zero1;
        return $time_c;
    }

    /**
     * 简历弹出联系方式值
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function personContact(Request $request){
        $request->only('resumeId');
        $user=auth()->guard('company')->user();
        //简历是否被查看
        $lookStatus = $this->lookResumeStatus($user->uid,$request->resumeId);

        if(!empty($user->uid)){
            $resumeMoneyStatus =  $this->getContact($request->resumeId,$user->uid,$lookStatus);
            //0提示充值,1表示有简历数，输出联系方式
            if($resumeMoneyStatus[0] == 1){
                $mobile = $resumeMoneyStatus[1]['mobile'];
                $email = $resumeMoneyStatus[1]['email'];
                $qq = $resumeMoneyStatus[1]['qq'];
            }else{
                $mobile = '';
                $email = '';
                $qq = '';
            }

        }

        return response()->json(['status'=>$resumeMoneyStatus[0],'mobile'=>$mobile,'email'=>$email,'qq'=>$qq]);
    }

    /**
     * 企业发部岗位与发送面试邀请
     * @return \Illuminate\Http\JsonResponse
     */
    public function inviteInterview(){

        $user=auth()->guard('company')->user();
        if(!empty($user->uid)){
            $CompanyJob = CompanyJob::select("id","com_id","job_title")->where('uid',$user->uid)->where('job_status','1')->get();
            $inviteTitle = [];
            if($CompanyJob and count($CompanyJob)>0 and $user->resumeNumber()<=0){
                $status = 2;
            }elseif($CompanyJob and count($CompanyJob)>0 and $user->resumeNumber()>0){
                foreach($CompanyJob as $k => $v){
                    //$inviteId[$k] = $v->id;
                    $inviteTitle[] = array(
                        'value'=>$v->id,
                        'text'=>str_limit($v->job_title,32)
                    );
                }
                $status = 1;
            }else{
                $status = 3;
            }

            $date=date('Y-m-d 10:00:00');
            $date=date_create($date);
            date_sub($date,date_interval_create_from_date_string("-1 days"));//当前时间加上一天
            $interViewTime = date_format($date,"Y-m-d 10:00:00");

        }

        return response()->json(['status'=>$status,'inviteTitle'=>$inviteTitle,'interViewTime'=>$interViewTime]);
    }
}